<?php  namespace App\Models;

use App\Cache\MRedis;
use App\Models\User;
use Log;

class Comment extends BaseModel{
    
	//表明
	protected $table = 'comment';
	//主键
	protected $primaryKey = 'id';
        protected $mRedis;
        
    public function getCommentObject($Obj=null){
        $object = array();
        $id;
        $userId;
        if($Obj){
            $id = $Obj['id'];
            $object['commentId'] = $Obj['id'];
            $object['contentId'] = $Obj['content_id'];
            $object['parentId'] = $Obj['parent_id'];
            $object['type'] = 1;
            $object['replay'] = '';
            if($Obj['parent_id']){
                //父级评论的信息和人
                $mRedis = new MRedis();
                $CommObj = $mRedis->getEntity('comment', $Obj['parent_id']);//获取实体
                if($CommObj && isset($CommObj['id'])){
                    //获取用户实体
                    $userp = with(new User($this->request))->getRedisUserObject($CommObj['user_id']);
                    if($userp){
                        $object['type'] = 2;//如果是二级评论必须为2
                        $object['replay']['replayId'] = isset($userp['userId'])?$userp['userId']:'';
                        $object['replay']['replayName'] = isset($userp['nickname'])?$userp['nickname']:'';
                        $object['replay']['replayIcon'] = isset($userp['userIcon'])?$userp['userIcon']:'';
                        $object['replay']['contentId'] = isset($Obj['content_id'])?$Obj['content_id']:'';
                    }
                }
            }
            $object['content'] = $Obj['content'];
            $object['publishAt'] = $Obj['updated_at'];
            //获取用户实体
            $userObj = with(new User($this->request))->getRedisUserObject($Obj['user_id']);
            if($userObj){
                $object['userId'] = isset($userObj['userId'])?$userObj['userId']:'';
                $object['userName'] = isset($userObj['nickname'])?$userObj['nickname']:'';
                $object['userIcon'] = isset($userObj['userIcon'])?$userObj['userIcon']:'';
            }
            $object['contentId'] = $Obj['content_id'];
        }else{
            $id = $this->id;
            $object['commentId'] = $this->id;
            $object['contentId'] = $this->content_id;
            $object['parentId'] = $this->parent_id;
            $object['type'] = 1;
            $object['replay'] = '';
            if($this->parent_id){
                $user = $this->select('comment.id','comment.user_id','comment.parent_id','user.id as userId','user.name','user.img','comment.status','comment.is_delete')
                        ->join('user','comment.user_id','=','user.id')
                        ->where('comment.id','=',$this->parent_id)
                        ->where('user.status','=',1)
                        ->where('user.is_delete','=',0)
                        ->where('comment.is_delete','=',0)
                        ->where('comment.status','=',1)
                        ->first();
                if($user){
                    $object['type'] = 2;
                    $object['replay']['replayId'] = $user->userId;
                    $object['replay']['replayName'] = $user->name;
                    $object['replay']['replayIcon'] = $user->img;
                    $object['replay']['contentId'] = $user->id;
                }
            }
            $object['content'] = $this->content;
            $object['publishAt'] = $this->updated_at->timestamp;
            $object['userId'] = $this->user_id;
            $object['userName'] = $this->name;
            $object['userIcon'] = $this->img;
            $object['contentId'] = $this->content_id;
        }
        $object['isPraise'] = 0;
        $object['praiseTotal'] = 0;
        if(env('OPENCACHE', '0')){
            $userId = $this->request->input('userId');
            if($userId){
                $mRedis = new MRedis();
                $ret = $mRedis->IsPraiseComment($userId, $id);
                if($ret){
                    $object['isPraise'] = 1;
                }
                $sum = $mRedis->getCommentPraiseUserTotal($id);
                if($sum){
                    $object['praiseTotal'] = $sum;
                }
            }
        }
        return $object;
    }

    //获取内容下的评论列表
    public function getContentCommentList(){
        $userId = $this->request->input('userId');
        $contentId = $this->request->input('contentId');
        $page = $this->request->input('page');
        $size = $this->request->input('size');
        if(env('OPENCACHE', '0')){
            $mRedis = new MRedis();
            //判断取列表
            $ids = $mRedis->getCommentUserIdsByContentId($contentId, $page, $size);
            $size = count($ids);
            $data = [];
            $data['data'] = [];
            $data['paging']['size'] = 0;
            if($size > 0){
                foreach ($ids as $key => $val){
                    $temp = [];
                    $temp = explode('_', $key);
                    if(isset($temp[1])){
                        $temp = $this->getRedisCommentObject($temp[1]);
                        if($temp){
                            $data['data'][] = $temp;
                        }
                    }
                }
                if(is_array($data['data'])){
                    $data['paging']['size'] = $size;
                }
            }
            return $data;
        }else{
            $dataList = $this->select('comment.id','comment.user_id','comment.parent_id','user.name','user.img','comment.content_id','comment.content','comment.status','comment.is_delete','comment.updated_at')
                    ->join('user','user.id','=','comment.user_id')
                    ->where('user.status','=',1)
                    ->where('comment.content_id','=',$contentId)
                    ->where('comment.is_delete','=',0)
                    ->where('comment.status','=',1)
                    ->orderBy('comment.updated_at','desc')
                    ->skip($page*$size)
                    ->take($size)
                    ->get();
            $data = [];
            $data['data'] = [];
            $data['paging']['size'] = 0;
            foreach ($dataList as $val) {
                $val->request = $this->request;
                $data['data'][] = $val->getCommentObject();
            }
            if(is_array($data['data'])){
                $data['paging']['size'] = count($data['data']);
            }
            return $data;
        }
    }
    //获取我的评论
    public function getUserCommentList(){
        $userId = $this->request->input('userId');
        $uId = $this->request->input('uId');
        $page = $this->request->input('page');
        $size = $this->request->input('size');
        //getCommentContentIdsByUserId
        if(env('OPENCACHE', '0')){
            $mRedis = new MRedis();
            //判断取列表
            $ids = $mRedis->getCommentContentIdsByUserId($uId, $page, $size);
            $size = count($ids);
            $data = [];
            $data['data'] = [];
            $data['paging']['size'] = 0;
            if($size > 0){
                foreach ($ids as $key => $val){
                    $temp = [];
                    $temp = explode('_', $key);
                    if(isset($temp[1])){
                        $temp = $this->getRedisCommentObject($temp[1]);
                        if($temp){
                            $data['data'][] = $temp;
                        }
                    }
                }
                if(is_array($data['data'])){
                    $data['paging']['size'] = $size;
                }
            }
            return $data;
        }else{
            $dataList = $this->select('comment.id','comment.user_id','user.name','user.img','comment.content_id','comment.content','comment.status','comment.is_delete','comment.updated_at')
                    ->join('user','user.id','=','comment.user_id')
                    ->where('user.status','=',1)
                    ->where('comment.user_id','=',$uId)
                    ->where('comment.is_delete','=',0)
                    ->where('comment.status','=',1)
                    ->orderBy('comment.updated_at','desc')
                    ->skip($page*$size)
                    ->take($size)
                    ->get();
            $data = [];
            $data['data'] = [];
            $data['paging']['size'] = 0;
            foreach ($dataList as $val) {
                $val->request = $this->request;
                $data['data'][] = $val->getCommentObject();
            }
            if(is_array($data['data'])){
                $data['paging']['size'] = count($data['data']);
            }
            return $data;
        }
    }
    //发表评论
    public function createComment(){
        $userId = $this->request->input('userId');
        $contentId = $this->request->input('contentId');
        $content = $this->request->input('content');
        $commentId = $this->request->input('commentId');
        $type = $this->request->input('type');
        //校验内容敏感词
        if($type == 2){
            if(!$commentId){
                return FALSE;
            }
            $this->parent_id = $commentId;
        }
        //追加评论
        $this->user_id = $userId;
        $this->content_id = $contentId;
        $this->content = $content;
        $this->save();
        if(env('OPENCACHE', '0')){
            $mRedis = new MRedis();
            $ret = $mRedis->handleEntity('add', 'comment', $this->id);
            return $ret;
        }else{
            //追加评论数
            return $this->addCommentTotal($contentId);
        }
    }
    //发表评论
    public function deleteComment(){
        $userId = $this->request->input('userId');
        $commentId = $this->request->input('commentId');
        $contentId = $this->request->input('contentId');
        if(env('OPENCACHE', '0')){
            $mRedis = new MRedis();
            $ret = $mRedis->handleEntity('delete', 'comment', $commentId);
            return $ret;
        }else{
            $comment = Comment::select('id','user_id','content_id','status','is_delete')
                    ->where('id','=',$commentId)
                    ->first();
            if($comment){
                if($userId != $comment->user_id){
                    return FALSE;
                }
                if($comment->is_delete == 0){
                    $comment->is_delete = 1;
                }
                $ret = $comment->save();
                if(!$ret){
                    return FALSE;
                }
            }
            //追加评论数
            return $this->deleteCommentTotal($contentId);
        }
    }
    public function addCommentTotal($contentId){
        $obj = ContentStats::select('id','item_id','comment_total','play_total','praise_total','share_total','type','is_delete')
                ->where('item_id','=',$contentId)
                ->where('type','=',1)
                ->first();
        if($obj){
            $obj->comment_total += 1;
            if($obj->comment_total < 0){
                $obj->comment_total = 1;
            }
            $obj->is_delete = 0;
            $obj->save();
        }else{
            $newobj = new ContentStats();
            $newobj->comment_total = 1;
            $newobj->type = 1;
            $newobj->save();
        }
        return ['status'=>0];
    }
    public function deleteCommentTotal($contentId){
        $obj = ContentStats::select('id','item_id','comment_total','play_total','praise_total','share_total','type','is_delete')
                ->where('item_id','=',$contentId)
                ->where('type','=',1)
                ->first();
        if($obj){
            $obj->comment_total -= 1;
            if($obj->comment_total < 0){
                $obj->comment_total = 0;
            }
            $obj->is_delete = 0;
            $obj->save();
        }else{
            $newobj = new ContentStats();
            $newobj->comment_total = 0;
            $newobj->type = 1;
            $newobj->save();
        }
        return TRUE;
    }
     //获取redis的实体数据
    public function getRedisCommentObject($Id){
        $mRedis = new MRedis();
        $Obj = $mRedis->getEntity('comment', $Id);//获取实体
        if(!$Obj && $Id){
            Log::info("getRedisCommentObject:去数据库,id=".$Id);
            $ObjData = $this->select('comment.id','comment.user_id','comment.parent_id','comment.content_id','comment.content','comment.status','comment.is_delete','comment.updated_at')
                    ->where('comment.id', '=', $Id)
                    ->where('comment.is_delete','=',0)
                    ->where('comment.status','=',1)
                    ->first();
            if($ObjData){
                $ObjData->request = $this->request;
                return $ObjData->getCommentObject();
            }else{
                return FALSE;
            }
        }else{
//            Log::info("获取评论实体:". json_encode($Obj));
            return $this->getCommentObject($Obj);
        }
    }
}